# 执行SQL脚本
param(
    [string]$Server = "39.96.170.21",
    [string]$Database = "ManufacturingModel", 
    [string]$Username = "root",
    [string]$Password = "Knn123456",
    [string]$SqlFile = "backend-apis\CreateTables.sql"
)

Write-Host "开始执行数据库脚本..." -ForegroundColor Green
Write-Host "服务器: $Server" -ForegroundColor Yellow
Write-Host "数据库: $Database" -ForegroundColor Yellow
Write-Host "SQL文件: $SqlFile" -ForegroundColor Yellow

# 检查SQL文件是否存在
if (-not (Test-Path $SqlFile)) {
    Write-Host "❌ SQL文件不存在: $SqlFile" -ForegroundColor Red
    exit 1
}

# 读取SQL文件内容
$sqlContent = Get-Content $SqlFile -Raw
Write-Host "✅ SQL文件读取成功，内容长度: $($sqlContent.Length) 字符" -ForegroundColor Green

# 显示将要执行的SQL（前500字符）
Write-Host "`n将要执行的SQL内容（前500字符）:" -ForegroundColor Cyan
Write-Host $sqlContent.Substring(0, [Math]::Min(500, $sqlContent.Length)) -ForegroundColor Gray
if ($sqlContent.Length > 500) {
    Write-Host "..." -ForegroundColor Gray
}

# 确认执行
$confirm = Read-Host "`n是否继续执行SQL脚本？(y/N)"
if ($confirm -ne 'y' -and $confirm -ne 'Y') {
    Write-Host "操作已取消" -ForegroundColor Yellow
    exit 0
}

try {
    # 使用MySQL命令行工具执行SQL
    $mysqlCmd = "mysql -h$Server -u$Username -p$Password $Database"
    Write-Host "`n执行命令: $mysqlCmd < $SqlFile" -ForegroundColor Cyan
    
    # 注意：这需要系统中安装了MySQL客户端
    # 如果没有安装，需要手动在数据库管理工具中执行SQL
    Write-Host "`n⚠️  请手动在数据库管理工具中执行以下SQL:" -ForegroundColor Yellow
    Write-Host "连接信息:" -ForegroundColor Cyan
    Write-Host "  服务器: $Server" -ForegroundColor White
    Write-Host "  数据库: $Database" -ForegroundColor White
    Write-Host "  用户名: $Username" -ForegroundColor White
    Write-Host "  密码: $Password" -ForegroundColor White
    Write-Host "`nSQL文件位置: $SqlFile" -ForegroundColor White
    
} catch {
    Write-Host "❌ 执行失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

Write-Host "`n✅ 脚本准备完成！请手动执行SQL后继续下一步。" -ForegroundColor Green
